##last modified date: 2016.3.28
##author: dwliu

import subprocess
import os
import os.path
import datetime
import time
import sys
import logging




##find dirs in argv
def read_dirs():
	dirs = []
	for arg in sys.argv:
		dirs.append(arg)
	return dirs

##find dbspace_list using command 'onstat -d'
def find_dbspaces():
	#read dbspace
	try:
		#read stdout from pipe
		p = subprocess.Popen('onstat -d',stdin=subprocess.PIPE,stdout=subprocess.PIPE,stderr=subprocess.PIPE,shell=True)
		stdout = ''
		while True:
			line = p.stdout.readline()
			if line == '':
				break
			stdout+=line
		lines = stdout.split('\n')
		# Dbspaces
		# address          number   flags      fchunk   nchunks  pgsize   flags    owner    name
		# 100cd6028        1        0x40001    1        1        4096     N  BA    informix rootdbs
		
		# dbspace_list
		dbspace_list=[]
		for l in lines:
			tmp = l.split()
			if len(tmp) == 10:
				dbspace_list.append(tmp[9])
		
		return dbspace_list
	except Exception as e:
		print e

##find candicate files in dirs
def find_files(dirs):
	#find files for removement
	candicate_files = []
	for dir in dirs[1:]:
		if not os.path.exists(dir):
			print ("clean unused dbspace failed!")
			print ("not exists dir: "+dir)
			sys.exit(-1)
		if not os.path.isdir(dir):
			print ("clean unused dbspace failed!")
			print ("error: "+ dir+" is a file!")
			print ("please input a directory!")
			sys.exit(-1)
		for parent, dirnames, filenames in os.walk(dir):
			for filename in filenames:	
				candicate_files.append(parent+os.sep+filename)
		
	return candicate_files	
## clean unused dbspace files according to files and dbspace_list
def remove_file(candicate_files, dbspace_list):
	to_delete_files = []
	
	for filename in candicate_files:
		flag = False
		for dbspace in dbspace_list:
			if dbspace in filename:
				flag = True
				break
		if not flag:
			to_delete_files.append(filename)
	
	#remove file
	for filename in to_delete_files:
		#decide if the file is created in the same day of removement
		remove_day = datetime.datetime.fromtimestamp(time.time()).day
		create_day = datetime.datetime.fromtimestamp(os.path.getmtime(filename)).day
		if remove_day == create_day:
			print filename +' was created the same day of removement, should not be removed.'
			continue
		s
		print 'remove : ' + filename
		os.remove(filename)

if __name__ == "__main__":
	dirs = read_dirs()
	candicate_files = find_files(dirs)
	dbspace_list = find_dbspaces()
	remove_file(candicate_files, dbspace_list)